package com.ws.hzuoj.admin.system.menu.service.impl;

import com.ws.common.easyui.util.Page;
import com.github.pagehelper.PageHelper;
import com.ws.hzuoj.admin.system.menu.dao.MenuMapper;
import com.ws.hzuoj.admin.system.menu.entity.Menu;
import com.ws.hzuoj.admin.system.menu.service.IMenuService;
import com.ws.common.base.service.Impl.BaseServiceImpl;
import com.ws.user.permission.dao.PermissionMapper;
import com.ws.user.permission.entity.Permission;
import com.ws.user.permission.service.IPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService{

	@Autowired
	MenuMapper menuMapper;
	@Autowired
	IPermissionService permissionService;

	@Override
	public List<Menu> list(Menu params) {
		return menuMapper.list(params);
	}

	@Override
	public List<Menu> list(Menu params, Page page) {
		PageHelper.startPage(page.getPage(),page.getRows(),page.getOrder());
		return menuMapper.list(params);
	}

	@Override
	public Integer save(Menu menu) {
		return this.insertOrUpdate(menu);
	}

	@Override
	public List<Menu> menuList() {
		PageHelper.startPage(0,10000,"order_No asc");
		List<Menu> menus=menuMapper.list(new Menu());
		List<Menu> results=new ArrayList<Menu>();
		for(Menu m: menus){
			if(m.getPid().equals("0")){
				results.add(m);
			}
		}
		for(Menu root:results){
			for(Menu m: menus){
				if(m.getPid().equals(root.getId())){
					if(root.getChildren()==null){
						root.setChildren(new ArrayList<Menu>());
					}
					root.getChildren().add(m);
				}
			}
		}
		return results;
	}

	@Override
	public List<Menu> permissionTree() {
		List<Menu> menus=this.menuList();
		List<Permission> permissions=permissionService.listByMap(new HashMap<>());
		for(Permission permission:permissions){
			permission.setName("permission--"+permission.getName());
		}
		for(Menu menu: menus){
			if(menu.getChildren()!=null){
				for(Menu u: menu.getChildren()){
					menuAddPermission(u,permissions);
				}
			}
			menuAddPermission(menu,permissions);
		}
		return menus;
	}

	//把权限放到菜单下
	private void menuAddPermission(Menu menu,List<Permission> permissions){
		List<Menu> permis=new ArrayList<Menu>();
		for(Permission permission: permissions){
			if(menu.getId().equals(permission.getMenuId())){
				Menu u=new Menu();
				u.setId(permission.getId());
				u.setName(permission.getName());
				permis.add(u);
			}
		}
		if(permis.size()!=0){
			if(menu.getChildren()==null){
				menu.setChildren(new ArrayList<Menu>());
			}
			permis.addAll(menu.getChildren());
			menu.setChildren(permis);
		}
	}
}
